/*
	Level 관리용
	jquery, jquery-ui 필수
*/

(function($){
	$.fn.levelManage = function(p) {
	    
	    var liTag  = '<li class="_liClass" id="#id#" data="#data#" seq=#seq# top=#top#>#aTag# #inputTage#</li>';
		var aTag   = '<a href="#script#">#data# #imgTag#</a>';
		var imgTag = '<img src="#delOn#" class="#cls# del_btn" /> <img src="#editOn#" class="#cls# edit_btn" />';
		var inputTag = '<input type="text" value="#data#" id="#id#" name="levelName" style="display:none" />';
	    
		p = $.extend({
		    topId : '',                                                                 // top id
		    addBtnid : '',                                                              // add button id
		    selectedId : '',                                                            // selected li id
			drageable : true,                                                           // dragable flag
			dragableParentId : '',                                                      // dropabel tag id
			modable : true,                                                             // modify able flag
			data : {} ,                                                                 // LevelId:'', TopLevelId:'', LevelName:'', LevelSeq:',          // level datas
			btn_del_on : '/images/btn_delete_on.gif',                                   // delete button normal image
			btn_del_over : '/images/btn_delete_over.gif',                               // delete button mouse over image
			btn_edit_on : '/images/btn_edite_on.gif',                                   // edit button normal image
			btn_edit_over : '/images/btn_edite_over.gif',                               // edit button mouse over image
			imgClass : 'imgCl',                                                         // button class
			onclickFunction : null,                                                     // if data click event.. function.
			onmodifyFunction : null,                                                    // modify function
			onseqModifyFunction : null,                                                 // sequnce modify.. drag and drop
			refreshFunction : null,                                                     // refresh
			deleteFunction : null                                                       // delete function
		}, p);
		
		return this.each(function(){
		    var inThis = this;
			$(this).html('');       //clear
			
			if(p.data != null){ // if
			    // data 별
			    for(var i=0; i<p.data.length; i++){
			        var d = p.data[i];
			        // del / edit
			        var tempImgTag = imgTag.replace("#delOn#", p.btn_del_on);
			        tempImgTag = tempImgTag.replace("#editOn#", p.btn_edit_on);
			        tempImgTag = tempImgTag.replace(/#cls#/g, p.imgClass);
			        
			        // data
			        var tempATag = aTag.replace("#data#", d.LevelName).replace("#imgTag#", tempImgTag);
			        // input tag
			        var tmpInput = inputTag.replace("#data#", d.LevelName).replace("#id#", d.LevelId);
			        // li
			        var tempLiTag = liTag.replace("#aTag#", tempATag).replace("#id#", d.LevelId).replace("#seq#", i+1).replace("#top#", d.TopLevelId).replace("#data#", d.LevelName).replace("#inputTage#", tmpInput);
			        // append
			        $(this).append(tempLiTag);
			    }
			    
			    // imgeToggle
			    $("#" + p.dragableParentId + " ." + p.imgClass).each(function(){
                    var src = $(this).attr("src");
                    
                    $(this).mouseover(function(){
                        $(this).attr("src", src.replace("_on.gif", "_over.gif"));
                    });
                    $(this).mouseout(function(){
                        $(this).attr("src", src.replace("_over.gif", "_on.gif"));
                    });
                    
                    // when mouse over.. delete or edit button event..
                    $(this).click(function(){
                        var cls = $(this).attr("class") + "";
                        
                        var pLi = findParentLi(this);
                        var id = $(pLi).attr("id");
                        var data = $(pLi).attr("data");
                        var topId = $(pLi).attr("top");
                        
                        // delete button
                        if(cls.indexOf(" del") >= 0){
                            if(p.deleteFunction != null){
                                p.deleteFunction(id, topId);
                            }
                        }
                        
                        // edit button
                        else{
                            var input = $(pLi).find("#" + id);
                            $(pLi).attr("class", "edit");
                            $(pLi).find("a").hide();
                            $(input).show().val(data).focus();
                            
                            $(input).unbind('keyup').keyup(function(e){
                                // 저장
                                if(e.keyCode == 13){
                                    if(p.onmodifyFunction != null){
                                        if(confirm("저장하시겠습니까?")){
                                            var txt = $(input).val();
                                            if(txt == ""){
                                                alert("레벨 명을 입력하세요.");
                                                return;
                                            }
                                            p.onmodifyFunction(topId, id, txt);
                                        }
                                    }
                                }
                            });
                            
                            // 포커스 벗어나는 경우
                            $(input).focusout(function(e){
                                $(pLi).attr("class", "_liClass");
                                $(pLi).find("a").show();
                                $(input).hide();
                            });
                        }
                        // is Delete
                    });
                });
                
                // LI Objects of parent
                var liObj = $("#" + p.dragableParentId + " ._liClass");
                var parent = $(liObj).parent();
                
                // li mouse over
                $(liObj).mouseover(function(){
                    $(this).find("." + p.imgClass).each(function(){
                        $(this).show(); 
                    });
                });
                
                // li mouse out
                $(liObj).mouseout(function(){
                    $(this).find("." + p.imgClass).each(function(){
                        $(this).hide();
                    });
                });
                
                // click
                $(liObj).click(function(){
                    $(liObj).removeClass("on");
                    $(this).addClass('on');
                    var id = $(this).attr("id");
                    if(p.onclickFunction != null){
                        p.onclickFunction(id);
                    }
                });
                
                // drag and drop
                if(p.drageable){
                    var change = false;
                    $(parent).sortable(
                        {axis:"y"
                        , opacity:0.5
                        , containment:"document"
                        , cursor : "move"
                        , start : function(event, ui){
                            change = false;
                        }
                        , change : function(event, ui){
                            change = true;
                        }
                        , stop : function(event, ui){
                            if(change){
                                var param = "";
                                var lis = $(this).find("._liClass");
                                var topId = "";
                                var selectedId = "";
                                
                                for(var i=0; i<lis.length; i++){
                                    param += $(lis[i]).attr("id") + "," + (i+1) + "|";
                                    topId = $(lis[i]).attr("top");
                                    
                                    if(($(lis[i]).attr("class")+"").indexOf(" on") >= 0){
                                        selectedId = $(lis[i]).attr("id");
                                    }
                                }
                                    
                                var dragItem = ui.item;
                                if(confirm("순서를 변경 하시겠습나까?")){
                                    if(param != "" && p.onseqModifyFunction != null){
                                        p.onseqModifyFunction(topId, param, $(this).attr("id"), selectedId);
                                    }
                                }else{
                                    p.refreshFunction(topId, $(this).attr("id"), selectedId);
                                }
                            }
                        }
                    });
                }
                
                // add button click
                $("#" + p.addBtnid).unbind("click").click(function(){
                    var tmpInputTag = inputTag.replace("#data#", "").replace("#id#", "").replace("display:none", "display:");
                    var tmpLiTag = liTag.replace("_liClass", "edit").replace("#id#", "").replace("#seq#", i+1).replace("#top#", p.topId).replace("#data#", "").replace("#inputTage#", tmpInputTag).replace("#aTag#", "");
                    $(inThis).append(tmpLiTag);
                    var input = $(inThis).find(".edit input");
                    
                    $(input).keyup(function(e){
                        if(e.keyCode == 13){
                            if(p.onmodifyFunction != null){
                                if(confirm("저장하시겠습니까?")){
                                    var txt = $(input).val();
                                    if(txt == ""){
                                        alert("레벨 명을 입력하세요.");
                                        return;
                                    }
                                    p.onmodifyFunction(p.topId, "", txt);
                                }
                            }
                        }
                    }).focusout(function(e){
                        if(confirm("취소하시겠습니까?")){
                            $(inThis).find(".edit").remove();
                        }
                    }).focus();
                    
                });
			} // end if
			
			if(p.selectedId != ""){
                $("ul #" + p.selectedId).addClass("on");
            }
		});
		return this;
	};
})(jQuery);

// when del or edit button click.. find parent..
function findParentLi(ts){
    var p = null;
    var limit = 0;
    while(true){
        var t = $(ts).parent();
        if(($(t).attr("class")+"").indexOf("_liClass") >= 0){
            p = t;
            break;
        }
        ts = t;
        limit ++;
        if(limit >= 10){
            break;
            alert("Not found Parent Tag..");
        }
    }
    return p;
}